package com.gylang.print.richtext.processor;

import cn.hutool.core.collection.CollUtil;
import com.gylang.print.richtext.Coords;
import com.gylang.print.richtext.RichHelper;
import com.gylang.print.richtext.append.IRichAppend;
import com.gylang.print.richtext.pdf.RichPdfRender;
import com.gylang.print.richtext.resolver.StyleResolver;
import com.gylang.print.richtext.component.RichBox;
import com.gylang.print.richtext.component.BaseRich;
import com.gylang.print.richtext.component.BaseRichTable;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author gylang
 * data 2021/7/8
 */
public class TableProcessor implements IRichAppend, StyleResolver, RichPdfRender<BaseRichTable> {

	private static final String TABLE_TAG = "table";

	@Override
	public Element append(Element element, Map<String, Object> data) {

		// 判断是否为表格
		if (!TABLE_TAG.equals(element.tagName())) {
			return element;
		}
		// 获取每一行数据
		Elements elements = element.select("table tbody tr");
		// 占位替换
		if (CollUtil.isEmpty(elements)) {
			return element;
		}
		// 判断是否存在占位情况
		for (Element tr : elements) {
			// 正则获取所有的占位替换属性
			replaceAll(data, tr);
		}
		return element;
	}


	@Override
	public boolean resolve(Element element, List<BaseRich> component, BaseRich parent) {

		if (!TABLE_TAG.equals(element.tagName())) {
			return false;
		}
		// 解析表格数据
		// 获取每一行数据
		Elements elements = element.select("table tbody tr");

		// 判断是否存在占位情况
		BaseRichTable richTable = new BaseRichTable();
		richTable.copyStyle(parent);
		for (Element tr : elements) {
			// 解析文本样式
			Elements cells = tr.children();
			if (CollUtil.isNotEmpty(cells)) {
				List<List<BaseRich>> richStyles = new ArrayList<>();
				for (Element cell : cells) {
					List<BaseRich> cellStyle = RichHelper.style(cell);
					richStyles.add(cellStyle);
				}
				richTable.setRow(richStyles);
			}
			component.add(richTable);
		}
		return true;
	}

	@Override
	public Coords render(Coords lastNodeCoords, RichBox box, BaseRichTable richTable) {

		float sx = lastNodeCoords.ex();
		float sy = lastNodeCoords.ey();

		// 当前默认flexible

		return null;
	}
}
